import React,{useEffect,useState} from 'react';
import { PageHeader, Descriptions, message } from 'antd';
import axios from 'axios'
import moment from 'moment'
import { HeartTwoTone } from '@ant-design/icons'
const Details = (props) => {
 
  const [FormData, setFormData] = useState(null)
  useEffect(() => {
    axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
      setFormData({
        ...res.data,
        view:res.data.view+1
      })

      return res.data
    }).then(data => {
       axios.patch(`/news/${props.match.params.id}`, {
         view:data.view+1
       }).then(res => {
         setUser("view",data.view+1)
       })
    })
  }, [props.match.params.id])
  // 修改个人信息
  const setUser = (label, num) => {
    let obj = {}
    if (label === "view") {
      obj.view = num
    } else {
       obj.star = num
    }
    const {id} = JSON.parse(localStorage.getItem('token'))
    axios.patch(`/users/${id}`,obj)
  }
  // 点赞
  const fabulous = () => {
    // localStorage.setItem('FabulousNum',1)
    if (FormData.star>1 || FormData.star===1) {
      message.error('你已经点过赞了！')
    } else {
      if (FormData.star<1) {
        setFormData({
          ...FormData,
          star:FormData.star+1
        })
      
        axios.patch(`/news/${props.match.params.id}`, {
            star:FormData.star+1
        }).then(res => {
          setUser("star",FormData.star+1)
        })
      }
    }
  }
  return (
    <div>
      {
        FormData && <div>
          <PageHeader
            ghost={false}
            onBack={() => window.history.back()}
            title={FormData.title}
            subTitle={
              <div>
                <span style={{ paddingRight: "10px" }}>{FormData.category.title}</span>
                
                <HeartTwoTone twoToneColor={
                 FormData.star? "#eb2f96": "#6B676E"
                } onClick={() => fabulous()}/>
              </div>
            }
          >
            <Descriptions size="small" column={3}>
              <Descriptions.Item label="创建者">{FormData.author}</Descriptions.Item>
              <Descriptions.Item label="发布时间">{FormData.publishTime? moment(FormData.createTime).format("YYYY/MM/DD HH:mm:ss"):"---"} </Descriptions.Item>
              <Descriptions.Item label="区域">{FormData.region}</Descriptions.Item>
              <Descriptions.Item label="访问数量">{FormData.view}</Descriptions.Item>
              <Descriptions.Item label="点赞数量">{FormData.star}</Descriptions.Item>
              <Descriptions.Item label="评论数量">{0}</Descriptions.Item>
            </Descriptions>
          </PageHeader>
          <div dangerouslySetInnerHTML={{ __html: FormData.content }} style={{
            padding: "50px 24px",
            width: "80%",
            margin: "0 auto"
           }}></div>
        </div>
      }
    </div>
  );
}

export default Details;

